//
//  BHOAuthViewController.m
//  xinlangweibo0621
//
//  Created by boldseas on 2017/6/23.
//  Copyright © 2017年 renbohan. All rights reserved.
//

#import "BHOAuthViewController.h"
#import <Masonry.h>
#import <AFNetworking.h>
#import "BHAccount.h"
#import "BHTabBarViewController.h"
#import "BHNewfeatureController.h"
#import "BHAccountTool.h"
#import "UIWindow+BHExtension.h"

@interface BHOAuthViewController ()<UIWebViewDelegate, NSCoding>

@end

@implementation BHOAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIWebView *webView = [[UIWebView alloc]init];
    [self.view addSubview:webView];
    webView.delegate = self;
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(self.view);
    }];
    
    NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=3903537862&redirect_uri=http://"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *url = request.URL.absoluteString;
    NSRange range = [url rangeOfString:@"code="];
    if (range.length != 0) {
        int fromIndex = range.location + range.length;
        NSString *code = [url substringFromIndex:fromIndex];
        
        [self accessTokenWithCode:code];
        return NO;
    }
    
    return YES;
}

- (void)accessTokenWithCode:(NSString *)code{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    client_id 	string 	申请应用时分配的AppKey。
//    client_secret 	string 	申请应用时分配的AppSecret。
//    grant_type 	string 	请求的类型，填写authorization_code
//    code 	true 	string 	调用authorize获得的code值。
//    redirect_uri 	string 	回调地址，需需与注册应用里的回调地址一致。
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"client_id"] = @"3903537862";
    parameters[@"client_secret"] = @"6a3870bd433917f7052cc7e21ee2b78e";
    parameters[@"grant_type"] = @"authorization_code";
    parameters[@"code"] = code;
    parameters[@"redirect_uri"] = @"http://";
    [manager POST:@"https://api.weibo.com/oauth2/access_token" parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        BHAccount *account = [BHAccount accountWithDict:responseObject];
        [BHAccountTool saveAccount:account];
        
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        
        [window switchRootViewController];
        
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

@end
